<template>
  <div class="login-container">
    <h2>用户登录</h2>
    <form @submit.prevent="handleLogin" class="login-form">
      <div class="form-item">
        <label>用户名：</label>
        <input
          v-model="form.username"
          type="text"
          placeholder="请输入用户名"
          required
        />
      </div>
      <div class="form-item">
        <label>密码：</label>
        <input
          v-model="form.password"
          type="password"
          placeholder="请输入密码"
          required
        />
      </div>
      <button type="submit" :disabled="loading">
        {{ loading ? "登录中..." : "登录" }}
      </button>
    </form>

    <!-- 登录成功后显示用户信息 -->
    <div v-if="userInfo" class="user-info">
      <h3>登录成功！</h3>
      <p>欢迎你，{{ userInfo.name }}</p>
      <button @click="logout">退出登录</button>
    </div>

    <div v-if="error" class="error">
      {{ error }}
    </div>
  </div>
</template>

<script>
import { ref } from "vue";
import request from "@/utils/request";
import { useUserStore } from "../store/userStore";

export default {
  setup() {
    const form = ref({
      username: "",
      password: "",
    });

    const loading = ref(false);
    const error = ref("");
    const userInfo = ref(null);

    // 1. 登录方法
    const handleLogin = async () => {
      error.value = "";
      loading.value = true;
      try {
        // 假设你的登录接口是 /api/auth/login
        const res = await request.post("/api/auth/login", {
          username: form.value.username,
          password: form.value.password,
        });

        // 假设后端返回 { token: "xxx" }
        const token = res.token;
        const userStore = useUserStore(); // ✅ 调用函数，返回 store 实例
        userStore.setToken(token); // ✅ 再调用方法
        console.log("登录成功！" + useUserStore.Gettoken);
        if (!token) {
          error.value = "登录失败：未返回 token";
          return;
        }

        console.log("Token 已保存:", token);

        // 清空表单
        form.value.password = "";

        // 获取用户信息（测试是否通过拦截器）
        // await fetchUserInfo();
        console.log("用户信息：", userInfo.value);
      } catch (err) {
        error.value =
          "登录失败：" + (err.response?.data?.message || err.message);
      } finally {
        loading.value = false;
      }
    };

    // 2. 获取用户信息（测试拦截器是否放行）
    const fetchUserInfo = async () => {
      try {
        // 这个请求会自动带上 Authorization 头（Axios 拦截器）
        const data = await request.get("/api/auth/profile");
        userInfo.value = data;
      } catch (err) {
        error.value = "获取用户信息失败：" + err.message;
      }
    };

    // 3. 退出登录
    const logout = () => {
      localStorage.removeItem("token");
      userInfo.value = null;
      error.value = "已退出登录";
    };

    // 页面加载时，检查是否有 token，自动获取用户信息
    const init = () => {
      const token = localStorage.getItem("token");
      if (token) {
        fetchUserInfo();
      }
    };

    init();

    return {
      form,
      loading,
      error,
      userInfo,
      handleLogin,
      logout,
    };
  },
};
</script>

<style scoped>
.login-container {
  max-width: 400px;
  margin: 100px auto;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-family: Arial, sans-serif;
}

.form-item {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
  color: #333;
}

input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}

button {
  width: 100%;
  padding: 10px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

button:disabled {
  background-color: #999;
  cursor: not-allowed;
}

.user-info {
  margin-top: 20px;
  padding: 15px;
  background-color: #f0f8f0;
  border: 1px solid #c8e6c9;
  border-radius: 4px;
}

.error {
  margin-top: 15px;
  padding: 10px;
  background-color: #ffebee;
  color: #c62828;
  border: 1px solid #ef9a9a;
  border-radius: 4px;
}
</style>
